from common.utils.rights import permission_required, view_logging_required
from common.utils.file_read import file_read
from . import index_bp
from flask import render_template,request
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import cv2 as cv
import numpy as np


def pixGray(img):  # 直方图统计
    h = img.shape[0]
    w = img.shape[1]

    gray_level = np.zeros(256)
    gray_level2 = np.zeros(256)

    for i in range(1, h - 1):
        for j in range(1, w - 1):
            gray_level[img[i, j]] += 1  # 统计灰度级为img_gray[i,j]的个数

    for i in range(1, 256):
        gray_level2[i] = gray_level2[i - 1] + gray_level[i]  # 统计灰度级小于img_gray[i,j]的个数

    return gray_level2


def imgEqualize(img):  # 直方图均衡化
    h, w = img.shape
    gray_level2 = pixGray(img)
    lut = np.zeros(256)
    for i in range(256):
        lut[i] = 255.0 / (h * w) * gray_level2[i]  # 得到新的灰度级
    lut = np.uint8(lut + 0.5)
    out = cv.LUT(img, lut)
    return out
# 用户增加
@index_bp.get('/equal_pro')
@index_bp.post('/equal_pro')
@view_logging_required
@permission_required("equal:pro")
def equal_pro():
    if request.method == "GET":
        return render_template('admin/cv/equal.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']
            file_url = file_read(f)
            pic = cv.imread(file_url,0)
            res_pic = "static/download/equal.jpg"
            out_image = imgEqualize(pic)
            cv.imwrite(res_pic, out_image)
            return render_template('admin/cv/equal.html', pic=file_url, pic_res=res_pic)
        else:
            return "请传入正确的文件格式"
